package com.neuedu.boot.controller;

import com.neuedu.boot.entity.User;
import com.neuedu.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    //列表
    @RequestMapping("/list")
    String list(User user, Model model) {

        List<User> list = userService.list(user);

        model.addAttribute("userList", list);

        //配置前缀  /WEB-INF/views/
        //后缀    .jsp
        return "user/user_list";   //  /WEB-INF/views/user/user_list.jsp

    }

    /**
     * 有id的即为 编辑
     * 否则添加
     *
     * @return
     */
    @RequestMapping("/toEdit")
    String toEdit(Integer id, Model model) {
        //如果有id，查询数据
        if (!ObjectUtils.isEmpty(id)) {
            User user = userService.queryById(id);
            model.addAttribute("user", user);
        }


        return "user/user_edit";
    }


    //去添加 or 修改
    @PostMapping("/save")
    String save(User user) {

        boolean success = userService.save(user);

        if (success) {
            return "redirect:/user/list";
        } else {

            return "/user/toEdit";
        }

    }


    //根据主键删除
    @GetMapping("/del")
    String del(Integer id, Model model) {

        boolean success = userService.removeById(id);

        if (success) {
            return "redirect:/user/list";
        } else {

            return "/user/list";
        }

    }

    //根据主键删除
    @PostMapping("/ajaxDel")
    @ResponseBody
    Map ajaxDel(Integer id, Model model) {

        boolean success = userService.removeById(id);

        Map map = new HashMap();
        map.put("success", success);

        return map;
    }

    //删除的功能
}
